import dayjs from 'dayjs';

export default function createDateObjects(date, weekOffset = 1, daysCount = 42) {
  const startOfMonth = dayjs(date).startOf('month');

  let diff = startOfMonth.day() - weekOffset;
  if (diff < 0) diff += 7;

  const prevMonthDays = [];
  for (let i = 0; i < diff; i += 1) {
    prevMonthDays.push({
      day: startOfMonth.subtract(diff - i, 'day'),
      classNames: 'prevMonth',
    });
  }
  const currentMonthDays = [];
  for (let i = 1; i < date.daysInMonth() + 1; i += 1) {
    currentMonthDays.push({
      day: dayjs().year(date.year()).month(date.month()).date(i),
    });
  }

  const daysAdded = prevMonthDays.length + currentMonthDays.length - 1;
  const nextMonthDays = [];
  let i = 1;
  while (daysCount - daysAdded - i > 0) {
    nextMonthDays.push({
      day: currentMonthDays[currentMonthDays.length - 1].day.clone().add(i, 'day'),
      classNames: 'nextMonth',
    });

    i += 1;
  }
  return [...prevMonthDays, ...currentMonthDays, ...nextMonthDays];
}

export function create21Days(date) {
  const startOf = dayjs(date).startOf('week');
  const ret = [];
  for (let i = 0; i < 21; i += 1) {
    ret.push({ day: startOf.add(i, 'day') });
  }
  return ret;
}

export function create7Days(date) {
  const startOf = dayjs(date).startOf('week');
  const ret = [];
  for (let i = 0; i < 7; i += 1) {
    ret.push({ day: startOf.add(i, 'day') });
  }
  return ret;
}

// TODO be careful
export const numberChinese = (number) => {
  const units = '个十百千万@#%亿^&~';
  const chars = '零一二三四五六七八九';
  const a = `${number}`.split('');
  const s = [];
  const j = a.length - 1;
  if (a.length > 12) {
    throw new Error('too big');
  } else {
    for (let i = 0; i <= j; i += 1) {
      if (j === 1 || j === 5 || j === 9) {
        // 两位数 处理特殊的 1*
        if (i === 0) {
          if (a[i] !== '1') s.push(chars.charAt(a[i]));
        } else {
          s.push(chars.charAt(a[i]));
        }
      } else {
        s.push(chars.charAt(a[i]));
      }
      if (i !== j) {
        s.push(units.charAt(j - i));
      }
    }
  }
  // return s;
  return s
    .join('')
    .replace(/零([十百千万亿@#%^&~])/g, (_m, d, b) => {
      // 优先处理 零百 零千 等
      b = units.indexOf(d);
      if (b !== -1) {
        if (d === '亿') return d;
        if (d === '万') return d;
        if (a[j - b] === '0') return '零';
      }
      return '';
    })
    .replace(/零+/g, '零')
    .replace(/零([万亿])/g, (_m, b) => {
      // 零百 零千处理后 可能出现 零零相连的 再处理结尾为零的
      return b;
    })
    .replace(/亿[万千百]/g, '亿')
    .replace(/[零]$/, '')
    .replace(/[@#%^&~]/g, (m) => {
      return { '@': '十', '#': '百', '%': '千', '^': '十', '&': '百', '~': '千' }[m];
    })
    .replace(/([亿万])([一-九])/g, (m, d, b, c) => {
      c = units.indexOf(d);
      if (c !== -1) {
        if (a[j - c] === '0') return `${d}零${b}`;
      }
      return m;
    });
};
